<?php


namespace App\Repositories\Admin\User;


use App\Models\Role;
use App\Repositories\BaseRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class RoleRepository extends BaseRepository
{

    public function model()
    {
        // TODO: Implement model() method.
        return new Role();
    }
    public function pagination($where=[],$param=[])
    {
        return $this->model()->all();
    }

    public function create($data)
    {
        $role = $this->model();

        $created = DB::transaction(function ()use($data,$role){
            $role->name = $data['name'];
            $role->display_name = $data['display_name']??'未命名_'.time();
            $role->description = $data['description']??'';
            $created = $role->save();
            if(!$created){
                DB::rollBack();
                return false;
            }
            if(empty($data['permissions'])){
                return true;
            }

            $attached = $role->attachPermissions($data['permissions']);
            if(!$attached){
                DB::rollBack();
                return false;
            }
            $role->load(['permissions'])->refresh();
            return true;
        });
        return $created?$role:false;
    }

    public function allotPermission($permission, Role $role)
    {
        return $role->syncPermissions($permission);
    }
}
